package com.kfm.mvn.servlet;

import com.kfm.mvn.model.User;
import com.kfm.mvn.util.Constant;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

@WebServlet("/online")
public class OnlineServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = req.getServletContext();

        // 在线用户集合
        Map<String, HttpSession> map = (Map<String, HttpSession>) servletContext.getAttribute(Constant.ONLINE_USERS_KEY);

        // 迭代
        Collection<HttpSession> values = map.values();

        resp.setContentType("text/html;charset=utf-8");
        String html = """
                    <table width='800px' border='1px'>
                        <tr>
                            <th>序号</th>
                            <th>真实姓名</th>
                            <th>登录时间</th>
                            <th>上一次访问时间</th>
                            <th>操作</th>
                        </tr>
                """;
        int count = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (HttpSession session : values) {
            User user = (User) session.getAttribute(Constant.LOGIN_USER);
            long creationTime = session.getCreationTime();
            long lastAccessedTime = session.getLastAccessedTime();


            html += """
                        <tr>
                            <td>%d</td>
                            <td>%s</td>
                            <td>%s</td>
                            <td>%s</td>
                            <td>%s</td>                            
                        </tr>
                    """.formatted(++ count, user.getName(), sdf.format(new Date(creationTime)), sdf.format(new Date(lastAccessedTime))
            , "<a href='out?id=" + session.getId() +"'>下线</a>");
        }

        html += "</table>";

        resp.getWriter().write(html);
    }
}
